package backend.search.manager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.product.model.Product;
import core.util.HibernateCoreUtil;

public class ProductSearchManager extends HibernateCoreUtil{
	
	public List<Product> getSimpleSearchResult(String searchById,String searchByName)
	{
		List<Product> lstProd = new ArrayList<Product>();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Product product = null ;
		Iterator<Product> proItr;
		try 
		{
				transaction = session.beginTransaction();
				//from Category c where c.name='"+name+"' and c.path='"+path+"'")
				if((searchByName!=null && searchById!=null) && (searchByName.trim().length()!=0 && searchById.trim().trim().length()!=0))
				{
					proItr = session.createQuery("from Product product where ((product.sku like '%"+searchById+"%') and (product.name like ''%"+searchByName+"'))").list().iterator();
				}
				else if(searchById==null || searchById.trim().length()==0)
				{
					proItr = session.createQuery("from Product product where product.sku like '%"+searchByName+"%'").list().iterator();
				}
				else{
					proItr = session.createQuery("from Product product where product.sku like '%"+searchById+"%'").list().iterator();
					
				}

				while(proItr.hasNext())
				{
					product = proItr.next() ;
					lstProd.add(product);
				}
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return lstProd;
	}
	

}
